Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
Is it possible to sort array with some "between" numbers?

Is it possible, somehow, to sort array with some "between" numbers?

[31, 33/34, 34, 29].sort((a, b) => a.toString().localeCompare(b.toString()))

//to return [29, 31, 33/34, 34] instead [0.9705882352, 29, 31, 34]

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As mentioned in the comments, the only way this will work is if you use string to capture the numbers. The engine is going to store your 33/34 as the decimal. There is no way to get the original value back.

Doing it is just a simple parse and sort.

var nums = ['31', '33/34', '34', '29']

nums.sort((a, b) => Number(a.split('/')[0]) - Number(b.split('/')[0]));

console.log(nums);

Now you may need to add more logic if you can have multiple numbers to push the 33/34 to the right spot. Not knowing all of the use cases, I am going to not try to guess.

about 4 years ago · Juan Pablo Isaza Relatório

0

When converting to string your are converting the fraction 33/34 (=0.9705882352). That's all that's visible the JS interpreter: it does not matter whether you provided 0.9705882352 or 33/34 or 66/68. So as indicated by @ninascholz & @epascarello, you have to start off with strings. With strings, your code should work fine as in the demo below:

const nums = ['31', '33/34', '34', '29']

nums.sort((a, b) => a.localeCompare(b));

console.log( nums );

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda